import sys
import time
import math
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QPainter, QPen
from PyQt5.QtCore import Qt, QPoint
from pynput import mouse

pressing = False
start_time = None
line_length = 0
start_point = None
scaling_factor = 0.4  # 每毫秒增长多少px
show_helper = True    # 是否显示辅助线，默认开启

class TransparentOverlay(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowFlags(
            Qt.FramelessWindowHint |
            Qt.WindowStaysOnTopHint |
            Qt.Tool |
            Qt.WindowTransparentForInput  # 鼠标穿透
        )
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.showFullScreen()

    def paintEvent(self, event):
        if start_point and line_length > 0 and show_helper:
            qp = QPainter()
            qp.begin(self)
            pen = QPen(Qt.red, 2)
            qp.setPen(pen)

            # 画右上 -35°
            radians_r = math.radians(-35)
            end_rx = start_point.x() + math.cos(radians_r) * line_length
            end_ry = start_point.y() + math.sin(radians_r) * line_length
            qp.drawLine(start_point, QPoint(int(end_rx), int(end_ry)))

            # 画左上 -145°
            radians_l = math.radians(-145)
            end_lx = start_point.x() + math.cos(radians_l) * line_length
            end_ly = start_point.y() + math.sin(radians_l) * line_length
            qp.drawLine(start_point, QPoint(int(end_lx), int(end_ly)))

            qp.end()

    def update_overlay(self):
        self.update()

def on_click(x, y, button, pressed):
    global pressing, start_time, line_length, start_point, show_helper
    if pressed:
        if button.name == 'left':
            pressing = True
            start_time = time.time()
            line_length = 0
            start_point = QPoint(x, y)
            print(f"起点：{start_point.x()}, {start_point.y()}")
        elif button.name == 'middle':  # 中键切换辅助线显示开关
            show_helper = not show_helper
            status = "开启" if show_helper else "关闭"
            print(f"辅助线显示已{status}")
    else:
        if button.name == 'left':
            pressing = False
            start_point = None
            line_length = 0

def main():
    global pressing, start_time, line_length

    app = QApplication(sys.argv)
    overlay = TransparentOverlay()

    listener = mouse.Listener(on_click=on_click)
    listener.start()

    while True:
        if pressing and start_point:
            elapsed = (time.time() - start_time) * 1000
            line_length = int(elapsed * scaling_factor)

        overlay.update_overlay()
        app.processEvents()
        time.sleep(0.01)

if __name__ == '__main__':
    main()
